#ifndef __UDP_SEVER_HPP__
#define __UDP_SEVER_HPP__

#include "logmessage.hpp"
#include <string>
#include <unordered_map>
#include <cstdio>
#include <cstring>
#include <cerrno>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <signal.h>
#include <cstdlib>
#include <fcntl.h>

#define DEV "dev/null"

class UdpServer
{
    int _sockfd;
    uint16_t _port;
    std::string _ip;
    std::unordered_map<std::string, sockaddr_in> _users;

public:
    UdpServer(const std::string &ip, const uint16_t port)
        : _ip(ip),
          _port(port),
          _sockfd(-1)
    {
    }

    void InitServer()
    {
        // 1.创建套接字文件描述符
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd == -1)
        {
            LogMessage(FATAL, "(%d)%s", errno, strerror(errno));
            exit(errno);
        }

        // 2.手动绑定文件描述符和套接字结构
        // 将用户设置的ip和port在内核中和当前进程强关联
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = inet_addr(_ip.c_str());
        int ret = bind(_sockfd, (struct sockaddr *)&local, sizeof(local));
        if (ret == -1)
        {
            LogMessage(FATAL, "(%d)%s", errno, strerror(errno));
            exit(errno);
        }

        LogMessage(DEBUG, "init server success!");
    }

    void Start()
    {
        char buffer[1024];
        char username[64];
        char msg[1024];

        for (;;)
        {
            sockaddr_in client;             // 输出型参数
            socklen_t len = sizeof(client); // 输入输出型参数：输入：client缓冲器的大小，输出：实际读到的client的大小
            memset(&client, 0, sizeof(client));
            ssize_t s = recvfrom(_sockfd, buffer, sizeof(buffer) - 1, 0, (sockaddr *)&client, &len);
            if (s > 0)
            {
                buffer[s] = 0;

                std::string client_ip = inet_ntoa(client.sin_addr); // 注意inet_ntoa的参数是sin_addr结构
                uint16_t client_port = ntohs(client.sin_port);
                snprintf(username, sizeof(username), "%s:%d", client_ip.c_str(), client_port);
                snprintf(msg, sizeof(msg), "[%s]# %s", username, buffer);
                if (_users.find(username) == _users.end())
                {
                    LogMessage(NORMAL, "%s log in!", username);
                    _users.insert({username, client});
                }
                printf("%s\n", msg);

            }

            // 2.群发消息
            for (auto &user : _users)
            {
                LogMessage(NORMAL, "push message: %s", user.first.c_str());
                sendto(_sockfd, msg, sizeof(msg), 0, (sockaddr *)&user.second, sizeof(user.second));
            }
            // printf("%s:%s -> %d\n", buffer, "quit", strcmp(buffer, "quit"));
            if (strcmp(buffer, "quit") == 0)
            {
                LogMessage(NORMAL, "%s log out!", username);
                _users.erase(username);
            }
        }
    }

    void Daemon(const char* logpath = DEV, const char* workpath = nullptr)
    {
        // 1.忽略异常信号
        signal(SIGPIPE, SIG_IGN);
        signal(SIGCHLD, SIG_IGN);
      
        // 2.创建子进程，父进程退出
        if(fork() > 0) exit(0);

        // 3.子进程建立新会话，脱离终端
        pid_t id = setsid();
        if(id == -1)
        {
          perror("setsid");
          exit(errno);
        }

        // 4.重定向到devnull或关闭原文件描述符
        int fd = open(logpath, O_RDWR);
        if(fd != -1)
        {
          dup2(fd, 0); //注意：此处含义相反，标准输入->devnull文件 : devnull的struct file指针复制给0号
          dup2(fd, 1);
          dup2(fd, 2);
        }
        else{
          close(0);
          close(1);
          close(2);
        }
        // 5.可选：切换工作目录
        if(workpath != nullptr)
        {
          chdir(workpath);
        }
    }

    ~UdpServer()
    {
        if (_sockfd >= 0)
            close(_sockfd);
    }
};

#endif
